<template>
  <view class="container">
    <view class="header">
      <text class="title">全部订单</text>
    </view>
    
    <view class="order-list" v-if="orders.length > 0">
      <view class="order-item" v-for="(order, index) in orders" :key="index">
        <view class="order-header">
          <text class="order-number">订单号: {{order.order ? order.order.orderid : order.orderId}}</text>
          <text class="order-status" :class="'status-' + getStatusClass(order.order ? order.order.state : order.status)">
            {{getStatusText(order.order ? order.order.state : order.status)}}
          </text>
        </view>
        
        <view class="order-content">
          <view class="land-info">
            <text class="land-name">{{order.land ? order.land.position : order.landName || '未知土地'}}</text>
            <text class="lease-time">租期: {{order.secondkill ? order.secondkill.leasetime : order.leaseTime || 0}}个月</text>
          </view>
          
          <view class="order-details">
            <view class="detail-row">
              <text class="label">下单时间:</text>
              <text class="value">{{formatDate(order.order ? order.order.createtime : order.createTime)}}</text>
            </view>
            <view class="detail-row">
              <text class="label">数量:</text>
              <text class="value">{{order.order ? order.order.num : order.num}}块</text>
            </view>
            <view class="detail-row">
              <text class="label">总价:</text>
              <text class="value price">¥{{order.order ? order.order.money : order.totalPrice || 0}}</text>
            </view>
          </view>
        </view>
        
        <view class="order-actions">
          <button 
            class="btn cancel" 
            v-if="order.order ? order.order.state === 0 : order.status === 0" 
            @click="cancelOrder(order.order ? order.order.orderid : order.orderId)">取消订单</button>
          <button 
            class="btn pay" 
            v-if="order.order ? order.order.state === 0 : order.status === 0" 
            @click="payOrder(order.order ? order.order.orderid : order.orderId)">立即支付</button>
          <button 
            class="btn detail" 
            @click="viewOrderDetail(order.order ? order.order.orderid : order.orderId)">查看详情</button>
        </view>
      </view>
    </view>
    
    <view class="empty-state" v-else-if="!loading">
      <image class="empty-image" src="http://121.36.197.175:19000/test/empty-order.png"></image>
      <text class="empty-text">暂无订单记录</text>
    </view>
    
    <view class="loading-container" v-else>
      <view class="loading-icon"></view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userId: '',
      orders: [],
      loading: false,

    }
  },
  onLoad() {
    // 获取用户ID，从登录信息中获取
    const userInfo = uni.getStorageSync('userInfo');
    // console.log('存储的用户信息: ', userInfo);
    
    if (userInfo && userInfo.userId) {
      this.userId = userInfo.userId;
    } else {
      // 如果没有用户ID，跳转到登录页面
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }
    
    // console.log('使用的用户ID: ', this.userId);
    this.fetchOrders();
  },
  onPullDownRefresh() {
    this.fetchOrders();
  },
  methods: {
    // 获取用户订单列表
    fetchOrders() {
      this.loading = true;
      uni.showLoading({
        title: '加载中...'
      });
      
      
      const apiUrl = '/secondkill/orders/' + this.userId;
      // console.log('请求订单API: ', apiUrl);
      
      this.$request({
        url: apiUrl,
        method: 'GET'
      }).then(res => {
        // console.log('后端返回数据: ', res);
        
        
        if (typeof res.data === 'string' && res.data.includes('<!DOCTYPE html>')) {
          throw new Error('服务器返回了错误页面，请检查API是否正确');
        }
        
        let originalOrders = [];
        
        // 解析不同格式的API响应
        if (res.data && res.data.orders) {
          originalOrders = res.data.orders;
        } else if (res.data && res.data.data && res.data.data.orders) {
          // {success: true, code: 200, data: {orders: [...]}}
          originalOrders = res.data.data.orders;
        } else if (Array.isArray(res.data)) {
          originalOrders = res.data;
        } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
          // {success: true, code: 200, data: [...]}
          originalOrders = res.data.data;
        }
        
        // 将原始订单数据映射为视图所需的格式
        this.orders = originalOrders.map(item => this.mapOrderData(item));
        
        // console.log('解析后的订单数据: ', this.orders);
        
        // 打印第一个订单项的详细信息，用于调试
        if (this.orders && this.orders.length > 0) {
          // console.log('映射后的第一个订单项:', JSON.stringify(this.orders[0]));
        }
        
        if (this.orders.length === 0) {
          uni.showToast({
            title: '暂无订单数据',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('获取订单失败', err);
        uni.showToast({
          title: err.message || '获取订单失败，请稍后重试',
          icon: 'none',
          duration: 3000
        });
        // 清空订单列表
        this.orders = [];
      }).finally(() => {
        this.loading = false;
        uni.hideLoading();
        uni.stopPullDownRefresh();
      });
    },
    
    // 支付订单
    payOrder(orderId) {
  uni.showModal({
    title: '确认支付',
    content: '是否确认支付该订单？',
    success: (res) => {
      if (res.confirm) {
        uni.showModal({
          title: '请输入支付密码',
          editable: true,
          passwordRes:  true,
          placeholderText: '请输入6位数字密码',
          success: (passwordRes) => {
            if (passwordRes.confirm) {
              // 手动验证输入是否为6位数字
              if (/^\d{6}$/.test(passwordRes.content)) {
                // 验证支付密码
                if (passwordRes.content === '123456') {
                  uni.showLoading({
                    title: '处理中...'
                  });
                  
                  const apiUrl = `/secondkill/pay/${orderId}`;
                  
                  this.$request({
                    url: apiUrl,
                    method: 'POST'
                  }).then(res => {
                    uni.showToast({
                      title: '支付成功',
                      icon: 'success'
                    });
                    this.fetchOrders();
                  }).catch(err => {
                    console.error('支付请求失败', err);
                    uni.showToast({
                      title: err.message || '支付失败，请稍后重试',
                      icon: 'none'
                    });
                  }).finally(() => {
                    uni.hideLoading();
                  });
                } else {
                  uni.showToast({
                    title: '支付密码错误',
                    icon: 'none'
                  });
                }
              } else {
                uni.showToast({ 
                  title: '请输入6位数字密码', 
                  icon: 'none' 
                });
              }
            }
          }
        });
        
        // 尝试强制设置为密码输入框
        setTimeout(() => {
          const inputs = document.querySelectorAll('.uni-modal input');
          if (inputs && inputs.length > 0) {
            inputs[0].type = 'password';
          }
        }, 300);
      }
    }
  });
},
    
    // 取消订单
    cancelOrder(orderId) {
      uni.showModal({
        title: '确认取消',
        content: '是否确认取消该订单？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '处理中...'
            });
            
            const apiUrl = `/secondkill/cancel/${orderId}`;
            
            this.$request({
              url: apiUrl,
              method: 'POST'
            }).then(res => {
              uni.showToast({
                title: '取消成功',
                icon: 'success'
              });
              this.fetchOrders();
            }).catch(err => {
              console.error('取消请求失败', err);
              uni.showToast({
                title: err.message || '取消失败，请稍后重试',
                icon: 'none'
              });
            }).finally(() => {
              uni.hideLoading();
            });
          }
        }
      });
    },
    
    // 查看订单详情
    viewOrderDetail(orderId) {
      // 尝试跳转到订单详情页
      try {
        uni.navigateTo({
          url: `/pages/my/orderDetail?orderId=${orderId}`,
          fail: () => {
            // 如果页面不存在，请求订单详情并显示
            this.fetchOrderDetail(orderId);
          }
        });
      } catch (e) {
        console.error('订单详情查看失败', e);
        // 获取详情并显示
        this.fetchOrderDetail(orderId);
      }
    },
    
    // 获取订单详情
    fetchOrderDetail(orderId) {
      uni.showLoading({
        title: '加载中...'
      });
      
      const apiUrl = `/secondkill/order/${orderId}`;
      
      this.$request({
        url: apiUrl,
        method: 'GET'
      }).then(res => {
        // 显示订单详情
        if (res.data && res.data.detail) {
          this.showOrderInfo(res.data.detail);
        } else if (res.data && res.data.data) {
          // 处理新的API响应格式
          this.showOrderInfo(res.data.data);
        } else {
          // 如果接口未返回详情，回退到当前列表中的订单信息
          const currentOrder = this.orders.find(order => 
            (order.orderId === orderId) || 
            (order.order && order.order.orderid === orderId)
          );
          if (currentOrder) {
            this.showOrderInfo(currentOrder);
          } else {
            uni.showToast({
              title: '获取订单信息失败',
              icon: 'none'
            });
          }
        }
      }).catch(err => {
        console.error('获取订单详情失败', err);
        // 回退到当前列表中的订单信息
        const currentOrder = this.orders.find(order => 
          (order.orderId === orderId) || 
          (order.order && order.order.orderid === orderId)
        );
        if (currentOrder) {
          this.showOrderInfo(currentOrder);
        } else {
          uni.showToast({
            title: '获取订单信息失败',
            icon: 'none'
          });
        }
      }).finally(() => {
        uni.hideLoading();
      });
    },
    
    // 直接显示订单信息
    showOrderInfo(order) {
      // 确保传入的是映射后的数据，如果是原始数据则需要处理
      let displayOrder = order;
      
      // 检查是否为原始数据结构(包含land、order和secondkill字段)
      if (order.land || order.order || order.secondkill) {
        const land = order.land || {};
        const orderData = order.order || {};
        const secondkill = order.secondkill || {};
        
        displayOrder = {
          orderId: orderData.orderid || '',
          landName: land.position || '未知土地',
          num: orderData.num || 1,
          leaseTime: secondkill.leasetime || 0,
          totalPrice: orderData.money || 0,
          status: orderData.state !== undefined ? orderData.state : 0,
          createTime: orderData.createtime || ''
        };
      }
      
      uni.showModal({
        title: '订单详情',
        content: `订单号: ${displayOrder.orderId}\n` +
                 `土地: ${displayOrder.landName || '未知'}\n` +
                 `数量: ${displayOrder.num}块\n` +
                 `租期: ${displayOrder.leaseTime || 0}个月\n` +
                 `总价: ¥${displayOrder.totalPrice || 0}\n` +
                 `订单状态: ${this.getStatusText(displayOrder.status)}\n` +
                 `下单时间: ${this.formatDate(displayOrder.createTime)}`,
        showCancel: false
      });
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已取消',
        3: '已完成'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取状态样式类名
    getStatusClass(status) {
      const statusMap = {
        0: 'pending',
        1: 'paid',
        2: 'canceled',
        3: 'completed'
      };
      return statusMap[status] || 'unknown';
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '暂无';
      
      try {
        const date = new Date(dateStr);
        return date.getFullYear() + '-' + 
               String(date.getMonth() + 1).padStart(2, '0') + '-' + 
               String(date.getDate()).padStart(2, '0') + ' ' + 
               String(date.getHours()).padStart(2, '0') + ':' + 
               String(date.getMinutes()).padStart(2, '0');
      } catch (e) {
        return dateStr;
      }
    },
    
    // 映射订单数据字段
    mapOrderData(item) {
      // 根据API返回的实际字段结构进行映射
      // API返回的数据包含三个主要对象: land, order, secondkill
      const land = item.land || {};
      const order = item.order || {};
      const secondkill = item.secondkill || {};
      
      return {
        orderId: order.orderid || '',
        status: order.state !== undefined ? order.state : 0,
        landName: land.position || '未知土地',
        leaseTime: secondkill.leasetime || 0,
        createTime: order.createtime || '',
        num: order.num || 1,
        totalPrice: order.money || 0
      };
    }
  }
}
</script>

<style>
.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.order-list {
  width: 100%;
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.order-number {
  font-size: 28rpx;
  color: #666;
}

.order-status {
  font-size: 28rpx;
  font-weight: bold;
}

.status-pending {
  color: #ff9800;
}

.status-paid {
  color: #4caf50;
}

.status-canceled {
  color: #999;
}

.status-completed {
  color: #2196f3;
}

.order-content {
  padding: 20rpx 0;
}

.land-info {
  margin-bottom: 20rpx;
}

.land-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}

.lease-time {
  font-size: 28rpx;
  color: #666;
}

.order-details {
  background-color: #f9f9f9;
  padding: 16rpx;
  border-radius: 8rpx;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 26rpx;
  color: #666;
}

.value {
  font-size: 26rpx;
  color: #333;
}

.price {
  color: #ff6b00;
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  gap: 20rpx;
}

.btn {
  padding: 12rpx 30rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  line-height: 1.5;
  text-align: center;
}

.btn.cancel {
  background-color: #f5f5f5;
  color: #666;
}

.btn.pay {
  background-color: #ff6b00;
  color: #fff;
}

.btn.detail {
  background-color: #2196f3;
  color: #fff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 100rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 30rpx;
  color: #999;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 100rpx;
}

.loading-icon {
  width: 44rpx;
  height: 44rpx;
  border-radius: 50%;
  border: 4rpx solid #2196f3;
  border-top-color: transparent;
  animation: spin 0.8s linear infinite;
}

.loading-text {
  font-size: 30rpx;
  color: #999;
  margin-top: 20rpx;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>